import { View, Text, Image, ScrollView } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import Taro from '@tarojs/taro'
import { useState } from 'react'
import './index.scss'
// 由于找不到 ScrollView，需要先从 @tarojs/components 导入

export default function Index() {
  // 定义新闻数据接口（匹配实际接口返回结构）
  interface NewsData {
    date: string
    news: string[]
    weiyu: string
    image: string
    head_image: string
  }

  const [newsData, setNewsData] = useState<NewsData | null>(null)
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    Taro.request({
      url: 'https://v3.alapi.cn/api/zaobao',
      method: 'GET',
      data: {
        token: 'ycd0krwbhl5v2w6iafblj94y5vzqdj',
        format: 'json'
      }
    }).then(res => {
      if (res.data.success) {
        setNewsData(res.data.data)
      }
      setLoading(false)
    }).catch(() => {
      setLoading(false)
    })
  })

  if (loading) {
    return <View className='index'><Text>加载中...</Text></View>
  }

  if (!newsData) {
    return <View className='index'><Text>获取资讯失败</Text></View>
  }

  const handleHeadImageClick = () => {
    console.log('点击头部图片时的image参数:', newsData.image);
    if (!newsData.image) {
      Taro.showToast({
        title: '图片地址不存在',
        icon: 'none'
      });
      return;
    }
    Taro.navigateTo({
      url: `/pages/detail/index?image=${encodeURIComponent(newsData.image)}`,
      success: () => console.log('导航到详情页成功'),
      fail: (err) => console.error('导航到详情页失败:', err)
    });
  };

  return (
    <View className='index'>
      <ScrollView className='news-list' scrollY>
        <Text className='date'>{newsData.date}</Text>
        <Text className='weiyu'>【微语】{newsData.weiyu}</Text>
        <Image className='head-image' src={newsData.head_image} mode='widthFix' onClick={handleHeadImageClick} />


        {newsData.news.map((item, index) => (
          <Text key={index} className='news-item'>{index + 1}、{item}</Text>
        ))}
      </ScrollView>


    </View>
  )
}
